1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.eventbus;
18  
19  import com.google.common.collect.Lists;
20  
21  import junit.framework.TestCase;
22  
23  import java.util.List;
24  
25  /**
26   * Validate that {@link EventBus} behaves carefully when listeners publish
27   * their own events.
28   *
29   * @author Jesse Wilson
30   */
31  public class ReentrantEventsTest extends TestCase {
32  
33    static final String FIRST = "one";
34    static final Double SECOND = 2.0d;
35  
36    final EventBus bus = new EventBus();
37  
38    public void testNoReentrantEvents() {
39      ReentrantEventsHater hater = new ReentrantEventsHater();
40      bus.register(hater);
41  
42      bus.post(FIRST);
43  
44      assertEquals("ReentrantEventHater expected 2 events",
45          Lists.<Object>newArrayList(FIRST, SECOND), hater.eventsReceived);
46    }
47  
48    public class ReentrantEventsHater {
49      boolean ready = true;
50      List<Object> eventsReceived = Lists.newArrayList();
51  
52      @Subscribe
53      public void listenForStrings(String event) {
54        eventsReceived.add(event);
55        ready = false;
56        try {
57          bus.post(SECOND);
58        } finally {
59          ready = true;
60        }
61      }
62  
63      @Subscribe
64      public void listenForDoubles(Double event) {
65        assertTrue("I received an event when I wasn't ready!", ready);
66        eventsReceived.add(event);
67      }
68    }
69  
70    public void testEventOrderingIsPredictable() {
71      EventProcessor processor = new EventProcessor();
72      bus.register(processor);
73  
74      EventRecorder recorder = new EventRecorder();
75      bus.register(recorder);
76  
77      bus.post(FIRST);
78  
79      assertEquals("EventRecorder expected events in order",
80          Lists.<Object>newArrayList(FIRST, SECOND), recorder.eventsReceived);
81    }
82  
83    public class EventProcessor {
84      @Subscribe public void listenForStrings(String event) {
85        bus.post(SECOND);
86      }
87    }
88  
89    public class EventRecorder {
90      List<Object> eventsReceived = Lists.newArrayList();
91      @Subscribe public void listenForEverything(Object event) {
92        eventsReceived.add(event);
93      }
94    }
95  }